package cn.saddyfire.pattern.factory.config_factory;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Properties;

/**
 * @author Dee
 * @date 2024/1/22
 * <p>Description:
 */
public class CoffeeFactory {
    //加载配置文件, 获取配置文件中配置的全类名, 并创建该类的对象进行存储
    //1.定义容器对象存储咖啡对象
    private static HashMap<String, Coffee> map = new HashMap<>();

    //2.加载配置文件, 只需要加载一次, 因此放在静态代码块里
    static {
        //2.1 创建Properties对象
        Properties p = new Properties();
        //2.2 调用p对象中的load方法进行配置文件的加载
        InputStream is = CoffeeFactory.class.getClassLoader().getResourceAsStream("bean.properties");
        try {
            p.load(is);
            //从p集合中获取全类名并创建对象
            for (Object key : p.keySet()) {
                String className = p.getProperty((String) key);
                Class<?> clazz = Class.forName(className);
                //无参构造
                Coffee coffee = (Coffee) clazz.newInstance();
                map.put((String) key, coffee);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Coffee craeteCoffee(String name) {
        return map.get(name);
    }
}
